<?php
    
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
     
/**
 * Description of ItemForm
 *
 * @author WIN7
 */
     
class ItemForm extends CFormModel
{
        public $name;
        public $image;
        public $IdCategory;
        public $price;
        public $description;
        public $discount;
        public $unit;
        public $sub_image;
        private $max_size = '2000';
            
//        private $_identity;
        /**
	 * Declares the validation rules.
	 * 
	 * 
	 */
	public function rules()
	{
		return array(
                    
			array('IdCategory, name, price, description, discount, unit, sub_image', 'required'),
                                                         array('image', 'file','types'=>'jpg, gif, png', 'allowEmpty'=>true, 'on'=>'update'),
                                                         array('title, image', 'length', 'max'=>255, 'on'=>'insert,update'),
		);
	}
            
	/**
	 * Declares attribute labels.
	 */
             
        public function attributeLabels()	{          
        }            
            
        private function getExtention($filename) {
            $pos = strpos($filename,".");
//            echo var_dump($pos);
            if (!$pos) return "";
            else {
            $length = strlen($filename) - $pos;
//            echo var_dump($length);
            $ext = substr($filename, $pos + 1, $length);
            return $ext;
            }        
            }
        private function uploadImage() {
            //upload multi
            $list = array();
            $uploadir = 'files/';
            $validformat = array("jpg","png","bmp","gif","jpeg");
            foreach ($_FILES['ItemForm']['name'] as $name => $value) {
                $file = stripcslashes($_FILES['ItemForm']['name'][$name]);
//                $path = $_FILES['ItemForm']['name'][$name];
//                $new = explode('/', $path);
                $ext = $this->getExtention($file);           
                $ext = strtolower($ext);                
//                $filename = substr($name, 0,strlen($name)-strlen($ext)-1);
//                var_dump($filename);
//                var_dump($ext);
                $size = filesize($_FILES['ItemForm']['tmp_name'][$name]);
//                echo var_dump($size);
//                echo var_dump($ext);
//                echo var_dump($file);
//                break;
                if (in_array($ext, $validformat)) {
                    if ($size < $this->max_size*1024) {
                        $image = time().$file;
                        $newname = $uploadir.$image;
                        if (move_uploaded_file($_FILES['ItemForm']['tmp_name'][$name], $newname))
                           $list[] = $image;
                        else {
                            $this->addError('sub_image', "'{$value}': Error. Moving unsuccessful. Please select other image.");
//                            echo "Moving unsuccessful";
//                            exit();
                        }
                    }
                    else {
                        $this->addError('sub_image', "'{$value}': Error. File too big. Please select other image.");
//                      echo "File too big";
//                      exit();
                    }
                } else {
                    $this->addError('sub_image',"'{$value}': Error. Unknown extension. Only allow jpg,png,bmp,gif or jpeg");
//                    echo "Unknown extension";
//                    exit();
                }                
                    }
            return $list;            
                    }
                    public function NewUpload() {
                        $list = array();
            $uploadir = 'files/';
            $validformat = array("jpg","png","bmp","gif","jpeg");
//            foreach ($_FILES['ItemForm']['name'] as $name => $value) {
//                $file = stripcslashes($_FILES['ItemForm']['name']);
//                $path = $_FILES['ItemForm']['name'][$name];
//                $new = explode('/', $path);
            $file =$_FILES['ItemForm']['name']['file'];
                $ext = $this->getExtention($file);           
                $ext = strtolower($ext);                
//                $filename = substr($name, 0,strlen($name)-strlen($ext)-1);
//                var_dump($filename);
//                var_dump($ext);
                $size = filesize($_FILES['ItemForm']['tmp_name']['file']);
//                echo var_dump($size);
//                echo var_dump($ext);
//                echo var_dump($file);
//                break;
                if (in_array($ext, $validformat)) {
                    if ($size < $this->max_size*1024) {
                        $image = time().$file;
                        $newname = $uploadir.$image;
                        if (move_uploaded_file($_FILES['ItemForm']['tmp_name']['file'], $newname)) 
//                                return $image;
                           $list[] = $image;
                        else {
                            $this->addError('sub_image', "'{$file}': Error. Moving unsuccessful. Please select other image.");
//                            echo "Moving unsuccessful";
//                            exit();
                            return FALSE;
                        }
                    }
                    else {
                        $this->addError('sub_image', "'{$file}': Error. File too big. Please select other image.");
//                      echo "File too big";
//                      exit();
                return FALSE;
                    }
                } else {
                    $this->addError('sub_image',"'{$file}': Error. Unknown extension. Only allow jpg,png,bmp,gif or jpeg");
//                    echo "Unknown extension";
//                    exit();
            return FALSE;
                }                
                    }
                    public function add(){            
                        try{
                                 $connection=Yii::app()->db;   // assuming you have configured a "db" connection  
//                                 echo var_dump($list);
//                                 echo var_dump(gettype($list));
                                 $list_image = json_encode($this->uploadImage());
//                                 break;
//                                 echo var_dump($_FILES);
//                                 break;
//                                 $list_image =  $this->sub_image;
                                 if (!$this->hasErrors()) {
//                                 echo var_dump($list);
//                                 echo var_dump(gettype($list));
                                 $query="INSERT INTO os_item(NameItem,IdCategory,Price,Description,LinkImage,Discount,Unit,sale_id,list_image) 
                                     VALUE('{$this->name}','{$this->IdCategory}','{$this->price}','{$this->description}','{$this->image}','{$this->discount}','{$this->unit}',".Yii::app()->session['saleId'].",'{$list_image}')";
                                 $connection->createCommand($query)->query(); 
                                 return true;
                                 }
                                 else                                     
                                     return FALSE;
                       }catch(Exception $e){
                                 $result=array('data'=>'','status'=>'fail','error'=>$e->getMessage());
                                 echo $string=json_encode($result);
                                 return FALSE;
                                 }                    
                        }
                        public function edit(){              
                        try{
                                 $connection=Yii::app()->db;   // assuming you have configured a "db" connection  
                                 //find Id from rowId in jqGrid
                                 $query_id="select os_item.Id, os_item.LinkImage, os_item.list_image from os_item 
                                     where os_item.sale_id =".Yii::app()->session["saleId"];
                                 $command_id = $connection->createCommand($query_id);
                                 $dataReader_id=$command_id->query();   
                                 $rows_item = array();
                                while(($row=$dataReader_id->read())!==false) {
                                    $rows_item[]=$row;
                                }
                                //Id in os_category table;
                                $rowId = $_GET['id']-1;
                                $idItem = $rows_item[$rowId]['Id'];
                                //update to database
                                if (!empty($rows_item[$rowId]['LinkImage']) && empty($this->image)) {
                                $this->image = $rows_item[$rowId]['LinkImage'];
                                }
                                //xử lý list_image
                                $list_image = json_decode($rows_item[$rowId]['list_image']);
//                                echo var_dump($list_image);
                                foreach ($_POST['ItemForm']['sub_image'] as $key => $value) {
                                    if (!empty($value)) {
//                                        echo var_dump($value);
                                        $part = explode('/', $value);
                                        $value = $part[count($part)-1];
                                        $list_image[$key] = $value; 
                                }}
//echo var_dump($list_image);
//                                break;
//                                if (!empty($_POST['ItemForm']['sub_image'])) {
//                                    if (!empty($list_image)) {
//                                        echo var_dump($_POST['ItemForm']['sub_image']);
//                                foreach ($list_image as $key => $value) {
//                                        $part = explode('/', $_POST['ItemForm']['sub_image'][$key]);
//                                        $list_image[$key] = $part[count($part)-1];
//                                    }
//                                    }else {
//                                        foreach ($_POST['ItemForm']['sub_image'] as $key => $value) {
//                                             echo var_dump($_POST['ItemForm']['sub_image']);
//                                        $part = explode('/', $_POST['ItemForm']['sub_image'][$key]);
//                                        $list_image[$key] = $part[count($part)-1];
//                                    }
//                                    }                                   
//                                }
//                                echo var_dump($list_image);
                                //thêm mới trong list_image
                                $list_image_new = $this->uploadImage();
                                //valid khi upload
                                if (!$this->hasErrors()) {                                         
                                $list_image =  array_merge($list_image, $list_image_new);
//                                echo var_dump($list_image_new);
//                                echo var_dump($list_image);
//                                break;
                                $list_image = json_encode($list_image);
                                $query="UPDATE os_item as a 
                                    SET a.NameItem='{$this->name}',a.IdCategory='{$this->IdCategory}',a.Price='{$this->price}',a.Description='{$this->description}', a.LinkImage='{$this->image}',a.Discount='{$this->discount}',a.Unit='{$this->unit}', a.list_image='{$list_image}' 
                                    WHERE a.Id=".$idItem; 
                                $connection->createCommand($query)->execute();
//                                $command->bindParam(":name",  $this->name,PDO::PARAM_STR);
//                                $command->bindParam(":mobile",  $this->mobile,PDO::PARAM_STR);
//                                $command->bindParam(":address",  $this->address,PDO::PARAM_STR);
//                                $command->bindParam(":lat",  $this->lat,PDO::PARAM_STR);
//                                $command->bindParam(":lng",  $this->lng,PDO::PARAM_STR);
//                                $command->bindParam(":image",  $this->image,PDO::PARAM_STR);
//                                $command->bindParam(":id",$store_id,PDO::PARAM_INT);
//                                $row_count=$command->execute();
//                                $resul=array('data'=>$json,'status'=>'ok');
//                                $string=json_encode($resul);
//                                echo $string;                                                              
                                return true;                                
                                    }
                                else
                                    return FALSE;                                     
                       }catch(Exception $e){
                                 $result=array('data'=>'','status'=>'fail','error'=>$e->getMessage());
                                 echo $string=json_encode($result);
                                 return FALSE;
                                 }                    
                        }
                        public function getItem($id) {
                            $connection = Yii::app()->db;
                            $sql = "select * from os_item where sale_id =".$id;
                            $data = $connection->createCommand($sql)->query();
                            $rows_item = array();
                            while ($row = $data->read()) {
                                $rows_item[] = $row;
                                }
                            return $rows_item;
                        }
}
?>